package br.com.jmmarca.controller;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import br.com.jmmarca.dao.impl.UsuarioDAO;
import br.com.jmmarca.model.Usuario;

public class Login extends Activity {

	private static final String TAG_LOG = "App_Login";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		Log.w(TAG_LOG, "onCreate!");
		// action_validar_usuario();
		// configurando o botão de criar novo cadastro
		Button btnLogar = (Button) findViewById(R.id.btn_enviar);
		btnLogar.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				action_validar_usuario();
			}
		});

		Button btnApresentar = (Button) findViewById(R.id.btn_exposicao);
		btnApresentar.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent goToNextActivity = new Intent(getApplicationContext(),
						LoginVisitante.class);
				startActivity(goToNextActivity);
			}
		});
	}

	public void action_validar_usuario() {
		final TextView username = (TextView) findViewById(R.id.txtLogin);
		final TextView password = (TextView) findViewById(R.id.txtSenha);
		String uname = username.getText().toString();
		String pass = password.getText().toString();

		if (uname.equals(getString(R.string.admin_login))
				&& pass.equals(getString(R.string.admin_pass))) {
			Log.w(TAG_LOG, "action_validar_usuario!");
			Intent goToNextActivity = new Intent(getApplicationContext(),
					MainAdmin.class).putExtra("usr", (CharSequence) uname);
			// Intent goToNextActivity = new Intent(getApplicationContext(),
			// CrudVisitante.class).putExtra("usr",(CharSequence)uname);
			startActivity(goToNextActivity);
		} else {
			UsuarioDAO usuarioDAO = UsuarioDAO
					.getInstance(getApplicationContext());
			try {
				List<Usuario> usuarios = usuarioDAO.listarPor("login=? and senha=?", new String[] {
						uname, pass });
				if(usuarios != null && usuarios.size()>0){
					Usuario usuario = usuarios.get(0);
					
					Intent goToNextActivity = new Intent(getApplicationContext(),
							MainAdmin.class).putExtra("usr", usuario.getNome());
					startActivity(goToNextActivity);
				}
				return;
			} catch (Exception e) {
			}
			Toast msg = Toast.makeText(this, "Usuário ou senha está incorreto",
					Toast.LENGTH_LONG);
			msg.show();
		}
	}
}
